/*
 * Copyright (C) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain an copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.xuexiang.xuidemo.slice.picker;

import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Component;
import ohos.agp.components.Image;
import ohos.agp.components.Text;
import ohos.agp.utils.Color;
import ohos.agp.utils.LayoutAlignment;
import ohos.agp.window.dialog.ToastDialog;
import ohos.multimodalinput.event.KeyEvent;

import com.xuexiang.xui_lib.component.button.SuperButton;
import com.xuexiang.xui_lib.component.picker.widget.BasePickerView;
import com.xuexiang.xui_lib.component.picker.widget.OptionsPickerView;
import com.xuexiang.xui_lib.component.picker.widget.TimePickerView;
import com.xuexiang.xui_lib.component.picker.widget.builder.OptionsPickerBuilder;
import com.xuexiang.xui_lib.component.picker.widget.builder.TimePickerBuilder;
import com.xuexiang.xui_lib.component.picker.widget.configure.TimePickerType;
import com.xuexiang.xui_lib.component.picker.widget.listener.OnDismissListener;
import com.xuexiang.xui_lib.component.picker.widget.listener.OnTimeSelectListener;
import com.xuexiang.xui_lib.component.picker.widget.utils.DateUtils;
import com.xuexiang.xui_lib.util.Log;
import com.xuexiang.xui_lib.util.StatusBarUtils;
import com.xuexiang.xuidemo.ResourceTable;
import com.xuexiang.xuidemo.util.AppCfig;
import com.xuexiang.xuidemo.util.DialogPickerValueChange;
import com.xuexiang.xuidemo.util.ToastUtil;
import com.xuexiang.xuidemo.view.DataPickerDialog;

import java.util.Calendar;
import java.util.Date;

/**
 * 描述 时间选择器
 *
 * @author ljc
 * @since 2021-04-23
 */
public class TimePickerAbilitySlice extends AbilitySlice implements Component.ClickedListener {
    private Image imageBack;
    private Text textTitle;
    private Text textTitleBottom;
    private SuperButton datePicker;
    private SuperButton dialogTimePicker;
    private SuperButton dialogTimePickerTop;
    private SuperButton dialogDataPickerSystem;
    private SuperButton dialogTimePickerSystem;
    private SuperButton dialogTimePickerClock;
    private SuperButton dialogTimePickerClockChina;
    private SuperButton dialogTimeperiodPicker;
    private Component mComponent;
    private String[] mTimeOption;
    private String[][] mTimeOption1;

    private Date mDate1;
    private Date mDate2;
    private Date mDate3;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        StatusBarUtils.translucent();
        StatusBarUtils.fullScreen();
        super.setUIContent(ResourceTable.Layout_ability_time_picker);
        initView();
    }

    private void initView() {
        findId();
        setClick();
        textTitle.setText("TimePicker");
        textTitleBottom.setText("时间选择器");
    }

    private void findId() {
        imageBack = (Image) findComponentById(ResourceTable.Id_image_back);
        textTitle = (Text) findComponentById(ResourceTable.Id_text_title);
        textTitleBottom = (Text) findComponentById(ResourceTable.Id_text_title_bottom);

        datePicker = (SuperButton) findComponentById(ResourceTable.Id_date_picker);
        dialogTimePicker = (SuperButton) findComponentById(ResourceTable.Id_dialog_time_picker);
        dialogTimePickerTop = (SuperButton) findComponentById(ResourceTable.Id_dialog_time_picker_top);
        dialogDataPickerSystem = (SuperButton) findComponentById(ResourceTable.Id_dialog_data_picker_system);
        dialogTimePickerSystem = (SuperButton) findComponentById(ResourceTable.Id_dialog_time_picker_system);
        dialogTimePickerClock = (SuperButton) findComponentById(ResourceTable.Id_dialog_time_picker_clock);
        dialogTimePickerClockChina = (SuperButton) findComponentById(ResourceTable.Id_dialog_time_picker_clock_china);
        dialogTimeperiodPicker = (SuperButton) findComponentById(ResourceTable.Id_dialog_timeperiod_picker);
        mComponent = (Component) findComponentById(ResourceTable.Id_component);
    }

    private void setClick() {
        imageBack.setClickedListener(this);
        datePicker.setClickedListener(this);
        dialogTimePicker.setClickedListener(this);
        dialogTimePickerTop.setClickedListener(this);
        dialogDataPickerSystem.setClickedListener(this);
        dialogTimePickerSystem.setClickedListener(this);
        dialogTimePickerClock.setClickedListener(this);
        dialogTimePickerClockChina.setClickedListener(this);
        dialogTimeperiodPicker.setClickedListener(this);
    }

    private void showDialog() {
        DataPickerDialog dataPickerDialog = new DataPickerDialog(getAbility());
        dataPickerDialog.setDialogPickerValueChange(new DialogPickerValueChange() {
            @Override
            public void valueChange(String message) {
                new ToastDialog(getContext())
                    .setText(message)
                    // Toast显示在界面中间
                    .setAlignment(LayoutAlignment.CENTER)
                    .show();
            }
        });
        dataPickerDialog.show();
    }

    @Override
    public void onClick(Component component) {
        switch (component.getId()) {
            case ResourceTable.Id_image_back:
                onBackPressed();
                break;
            /**
             * 日期选择器
             */
            case ResourceTable.Id_date_picker:
                showDatePicker();
                break;
            /**
             * 时间选择器
             */
            case ResourceTable.Id_dialog_time_picker:
                showTimePicker();
                break;
            /**
             * 弹框时间选择器
             */
            case ResourceTable.Id_dialog_time_picker_top:
                showTimePickerDialog();
                break;
            /**
             * 日期选择器(系统)
             */
            case ResourceTable.Id_dialog_data_picker_system:

                break;
            /**
             * 时间选择器(系统)
             */
            case ResourceTable.Id_dialog_time_picker_system:
                break;
            /**
             * 时间点选择器
             */
            case ResourceTable.Id_dialog_time_picker_clock:
                showTimePeriodPicker();
                break;
            /**
             * 时间点选择器(中式)
             */
            case ResourceTable.Id_dialog_time_picker_clock_china:
                showTimePeriodPicker1();
                break;
            /**
             * 时间段选择
             */
            case ResourceTable.Id_dialog_timeperiod_picker:
                showTimePeriodPicker2();
                break;
            default:
                break;
        }
    }

    private void showDatePicker() {
        mComponent.setVisibility(Component.VISIBLE);
        Calendar calendar = Calendar.getInstance();
        TimePickerView timePickerView = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelected(Date date, Component v) {
                mDate1 = date;
                ToastUtil.showToast(getContext(), DateUtils.date2String(date, DateUtils.yyyyMMdd.get()));
            }
        }).setTimeSelectChangeListener(date -> Log.i("pvTime", "onTimeSelectChanged"))
            .setTitleText("日期选择")
            .setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(BasePickerView pickerView) {
                    mComponent.setVisibility(Component.HIDE);
                }
            })
            .build();
        if (mDate1 != null) {
            calendar.setTime(mDate1);
        }
        timePickerView.setDate(calendar);
        timePickerView.show();
    }

    private void showTimePicker() {
        mComponent.setVisibility(Component.VISIBLE);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtils.getNowDate());
        TimePickerView timePickerView = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelected(Date date, Component v) {
                mDate2 = date;
                ToastUtil.showToast(getContext(), DateUtils.date2String(date, DateUtils.HHmmss.get()));
            }
        }).setTimeSelectChangeListener(date -> Log.i("pvTime", "onTimeSelectChanged"))
            .setType(TimePickerType.TIME)
            .setTitleText("时间选择")
            .setOnDismissListener(new OnDismissListener() {
                @Override
                public void onDismiss(BasePickerView pickerView) {
                    mComponent.setVisibility(Component.HIDE);
                }
            })
            .build();
        if (mDate2 != null) {
            calendar.setTime(mDate2);
        }
        timePickerView.setDate(calendar);
        timePickerView.show();
    }

    private void showTimePickerDialog() {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(DateUtils.string2Date("2013-07-08 12:32:46", DateUtils.yyyyMMddHHmmss.get()));
        TimePickerView timePickerView = new TimePickerBuilder(getContext(), new OnTimeSelectListener() {
            @Override
            public void onTimeSelected(Date date, Component v) {
                mDate3 = date;
                ToastUtil.showToast(getContext(), DateUtils.date2String(date, DateUtils.yyyyMMddHHmmss.get()));
            }
        }).setTimeSelectChangeListener(date -> Log.i("pvTime", "onTimeSelectChanged"))
            .setType(TimePickerType.ALL)
            .setTitleText("时间选择")
            .isDialog(false)
            .setOutSideCancelable(false)
            .build();
        if (mDate3 != null) {
            calendar.setTime(mDate3);
        }
        timePickerView.setDate(calendar);
        timePickerView.show();
    }

    private void showTimePeriodPicker() {
        if (mTimeOption == null) {
            mTimeOption = getTimePeriod(15);
        }

        //8点
        int defaultOption = 8 * 60 / 15;
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), (v, options1, options2, options3) -> {
            ToastUtil.showToast(this, mTimeOption[options1]);
            return false;
        })
            .setTitleText("时间点选择")
            .setSelectOptions(defaultOption)
            .build();
        pvOptions.setPicker(mTimeOption);
        pvOptions.show();
    }

    private void showTimePeriodPicker1() {
        if (mTimeOption1 == null) {
            mTimeOption1 = new String[5][];
            mTimeOption1[0] = getTimePeriod(0, 6, 15);
            mTimeOption1[1] = getTimePeriod(6, 6, 15);
            mTimeOption1[2] = getTimePeriod(12, 1, 15);
            mTimeOption1[3] = getTimePeriod(1, 5, 15);
            mTimeOption1[4] = getTimePeriod(6, 6, 15);
        }
        String[] option = new String[]{"凌晨", "上午", "中午", "下午", "晚上"};
        //8点
        int defaultOption = 2 * 60 / 15;
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), (v, options1, options2, options3) -> {
            ToastUtil.showToast(this, option[options1] + mTimeOption1[options1][options2]);
            return false;
        })
            .setTitleText("时间点选择")
            .isRestoreItem(true)
            .setSelectOptions(1, defaultOption)
            .build();
        pvOptions.setPicker(option, mTimeOption1);
        pvOptions.show();
    }

    private void showTimePeriodPicker2() {
        if (mTimeOption == null) {
            mTimeOption = getTimePeriod(15);
        }

        //8点
        int defaultOption = 8 * 60 / 15;
        OptionsPickerView pvOptions = new OptionsPickerBuilder(getContext(), (v, options1, options2, options3) -> {
            if (options1 > options2) {
                ToastUtil.showToasterror(getContext(), "  结束时间不能早于开始时间", new Color(AppCfig.one_black), ResourceTable.Media_ic_web_close, 0);
                //返回为true意为拦截，选择框不消失。
                return true;
            } else {
                ToastUtil.showToast(this, mTimeOption[options1] + "~" + mTimeOption[options2]);
                return false;
            }
        })
            .setTitleText("时间段选择")
            .setSelectOptions(defaultOption, defaultOption)
            .build();
        pvOptions.setNPicker(mTimeOption, mTimeOption);
        pvOptions.show();

    }

    /**
     * 获取时间段
     *
     * @param interval 时间间隔（分钟）
     * @return String[]
     */
    public static String[] getTimePeriod(int interval) {
        return getTimePeriod(24, interval);
    }

    /**
     * 获取时间段
     *
     * @param totalHour totalHour
     * @param interval 时间间隔（分钟）
     * @return return
     */
    public static String[] getTimePeriod(int totalHour, int interval) {
        String[] time = new String[totalHour * 60 / interval];
        int point, hour, min;
        for (int i = 0; i < time.length; i++) {
            point = i * interval;
            hour = point / 60;
            min = point - hour * 60;
            time[i] = (hour < 9 ? "0" + hour : "" + hour) + ":" + (min < 9 ? "0" + min : "" + min);
        }
        return time;
    }

    /**
     * 获取时间段
     *
     * @param startHour startHour
     * @param totalHour totalHour
     * @param interval 时间间隔（分钟）
     * @return return
     */
    public static String[] getTimePeriod(int startHour, int totalHour, int interval) {
        String[] time = new String[totalHour * 60 / interval];
        int point, hour, min;
        for (int i = 0; i < time.length; i++) {
            point = i * interval + startHour * 60;
            hour = point / 60;
            min = point - hour * 60;
            time[i] = (hour < 9 ? "0" + hour : "" + hour) + ":" + (min < 9 ? "0" + min : "" + min);
        }
        return time;
    }

    /**
     * 监听返回键
     *
     * @param keyCode
     * @param keyEvent
     * @return boolean
     */
    @Override
    public boolean onKeyUp(int keyCode, KeyEvent keyEvent) {
        mComponent.setVisibility(Component.HIDE);
        return super.onKeyUp(keyCode, keyEvent);
    }

}
